#!/usr/bin/env node

const { chromium } = require('playwright');
const fs = require('fs');
const path = require('path');

let context = null;
let page = null;
let userDataDir = path.join(__dirname, 'browser-data');

async function initialize() {
    if (!context) {
        console.log('初始化Playwright浏览器...');
        
        // 使用固定的用户数据目录
        context = await chromium.launchPersistentContext(userDataDir, {
            headless: false,
            args: [
                '--no-sandbox',
                '--disable-dev-shm-usage',
                '--disable-gpu',
                '--disable-extensions',
                '--disable-infobars',
                '--start-maximized',
                '--ignore-certificate-errors',
                '--ignore-ssl-errors'
            ],
            viewport: null,
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        });
        
        // 获取第一个页面，如果没有则创建新页面
        const pages = context.pages();
        if (pages.length > 0) {
            page = pages[0];
            console.log('使用现有页面');
        } else {
            page = await context.newPage();
            console.log('创建新页面');
        }
        
        console.log('浏览器初始化完成');
    }
}

async function openLoginPage() {
    await initialize();
    console.log('打开小红书登录页面...');

    try {
        await page.goto('https://creator.xiaohongshu.com/login', {
            waitUntil: 'networkidle',
            timeout: 30000
        });

        console.log('登录页面已打开，请手动完成登录...');
        console.log('登录完成后，请运行 check-status 命令检查状态');
        
        // 保持浏览器窗口打开，不要关闭
        console.log('浏览器窗口将保持打开状态，请勿关闭');
    } catch (error) {
        console.error('打开登录页面失败:', error.message);
        throw error;
    }
}

async function checkLoginStatus() {
    await initialize();
    console.log('检查登录状态...');

    try {
        // 等待页面加载
        await page.waitForLoadState('networkidle', { timeout: 10000 });

        let currentUrl = page.url();
        console.log(`当前URL: ${currentUrl}`);

        // 如果页面是空白，先导航到小红书
        if (currentUrl === 'about:blank' || currentUrl === '') {
            console.log('页面为空白，导航到小红书...');
            await page.goto('https://creator.xiaohongshu.com', {
                waitUntil: 'networkidle',
                timeout: 30000
            });
            currentUrl = page.url();
            console.log(`导航后URL: ${currentUrl}`);
        }

        // 检查是否在登录页面
        const isOnLoginPage = currentUrl.includes('login') || currentUrl.includes('creator.xiaohongshu.com/login');
        
        if (isOnLoginPage) {
            console.log('仍在登录页面，未登录');
            return false;
        }

        // 检查是否在创作者中心页面
        const isOnCreatorPage = currentUrl.includes('creator.xiaohongshu.com') && 
                               !currentUrl.includes('login') && 
                               (currentUrl.includes('creator') || currentUrl.includes('dashboard') || currentUrl.includes('publish') || currentUrl.includes('new/home'));

        if (isOnCreatorPage) {
            console.log('已登录，在创作者中心页面');
            return true;
        }

        // 检查页面内容
        const pageContent = await page.content();
        console.log('页面内容长度:', pageContent.length);
        
        // 检查是否有登录相关元素
        const hasLoginElements = pageContent.includes('login') || 
                               pageContent.includes('登录') || 
                               pageContent.includes('手机号') ||
                               pageContent.includes('验证码');
        
        // 检查是否有创作者中心元素
        const hasCreatorElements = pageContent.includes('创作者') || 
                                 pageContent.includes('发布') || 
                                 pageContent.includes('数据') ||
                                 pageContent.includes('dashboard') ||
                                 pageContent.includes('publish') ||
                                 pageContent.includes('new/home') ||
                                 pageContent.includes('笔记管理') ||
                                 pageContent.includes('数据看板');

        console.log('包含登录元素:', hasLoginElements);
        console.log('包含创作者元素:', hasCreatorElements);

        if (hasCreatorElements && !hasLoginElements) {
            console.log('已登录，检测到创作者中心元素');
            return true;
        }

        if (hasLoginElements) {
            console.log('未登录，检测到登录元素');
            return false;
        }

        console.log('登录状态不明确，URL:', currentUrl);
        return false;

    } catch (error) {
        console.error('检查登录状态时出错:', error.message);
        return false;
    }
}

async function getLoginInfo() {
    await initialize();
    console.log('获取登录信息...');

    try {
        const isLoggedIn = await checkLoginStatus();

        if (!isLoggedIn) {
            console.log('用户未登录');
            return {
                isLoggedIn: false,
                message: '用户未登录'
            };
        }

        const cookies = await context.cookies();

        let userInfo = null;
        try {
            // 尝试多种方式获取用户信息
            const userInfoSelectors = [
                '[data-testid="user-info"]',
                '.user-info',
                '.avatar',
                '.username',
                '.nickname',
                '[class*="user"]',
                '[class*="nickname"]',
                '.profile-name',
                '.user-name'
            ];
            
            for (const selector of userInfoSelectors) {
                const element = await page.$(selector);
                if (element) {
                    userInfo = await element.textContent();
                    if (userInfo && userInfo.trim()) {
                        console.log('找到用户信息:', userInfo);
                        break;
                    }
                }
            }
        } catch (e) {
            console.log('无法获取用户信息:', e.message);
        }

        const title = await page.title();
        const currentUrl = page.url();

        const loginInfo = {
            isLoggedIn: true,
            message: '登录成功',
            cookies: cookies,
            userInfo: userInfo,
            title: title,
            url: currentUrl
        };

        console.log('登录信息获取成功');
        return loginInfo;

    } catch (error) {
        console.error('获取登录信息时出错:', error.message);
        return {
            isLoggedIn: false,
            message: `获取登录信息失败: ${error.message}`
        };
    }
}

async function close() {
    console.log('关闭浏览器');
    if (context) {
        await context.close();
    }
    context = null;
    page = null;
}

// Command-line argument handling
const command = process.argv[2];

async function main() {
    try {
        switch (command) {
            case 'open-login':
                await openLoginPage();
                // 保持脚本运行，不要退出
                console.log('脚本将继续运行，浏览器窗口保持打开状态...');
                console.log('按 Ctrl+C 退出');
                // 保持进程运行
                process.stdin.resume();
                break;
            case 'check-status':
                const isLoggedIn = await checkLoginStatus();
                console.log(isLoggedIn ? 'true' : 'false');
                break;
            case 'get-info':
                const loginInfo = await getLoginInfo();
                console.log(JSON.stringify(loginInfo, null, 2));
                break;
            case 'close':
                await close();
                break;
            default:
                console.log('可用命令:');
                console.log('  open-login    - 打开登录页面');
                console.log('  check-status  - 检查登录状态');
                console.log('  get-info      - 获取登录信息');
                console.log('  close         - 关闭浏览器');
                console.log('');
                console.log('使用示例:');
                console.log('  node playwright-login.js open-login');
                console.log('  node playwright-login.js check-status');
                console.log('  node playwright-login.js get-info');
                break;
        }
    } catch (error) {
        console.error('执行失败:', error.message);
        process.exit(1);
    }
}

process.on('SIGINT', async () => {
    console.log('收到中断信号，正在关闭浏览器...');
    await close();
    process.exit(0);
});

process.on('SIGTERM', async () => {
    console.log('收到终止信号，正在关闭浏览器...');
    await close();
    process.exit(0);
});

main(); 